/**
 * AdminApplication - part of PerlaGis Architecture
 *
 * Copyright (C) 2010 Ricardo Gonzalez (gomnaz@gmail.com)
 * This program is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see http://www.gnu.org/licenses/
 */
package org.admin.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.admin.controllers.PerlaController;
import org.apache.taglibs.standard.tag.common.core.NullAttributeException;
import org.perla.services.Attitude;
import org.perla.services.Bibi;
import org.perla.services.Crackmeter;
import org.perla.services.NoSuchSensorException_Exception;
import org.perla.services.Sensori;
import org.perla.services.Temperature;
import org.perla.services.WrongSensorTypeException_Exception;

/**
 * Servlet che gestisce le operazioni sui valori.
 * Per il sensore <code>idSensore</code> del nodo <code>idNodo</code>, in base
 * al parametro <code>filter</code>, può eseguire le seguenti operazioni:
 * <ul>
 * <li><code>limit</code>: restituisce la lista dei valori con numero massimo pari a <code>limit</code></li>
 * <li><code>date</code>: Restituisce la lista dei valori registrati tra <code>from</code> e <code>to</code></li>
 * </ul>
 *
 * @author Ricardo Gonzalez
 * @author Eva Gjeci
 */
@WebServlet(name = "ValueActions", urlPatterns = {"/value"})
public class ValueServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String i = "";
        try {
            String filter = request.getParameter("filter");
            String idNodo = request.getParameter("idNodo");
            String idSensore = request.getParameter("idSensore");
            if (idNodo == null || idSensore == null) {
                throw new NullAttributeException("", "");
            }
            Sensori s = PerlaController.getSensor(idNodo, idSensore);
            i += "<type>" + s.getTiposensore().getNome() + "</type>";
            if (s.getTiposensore().getNome().equals("attitude")) {
                List<Attitude> l = null;
                if (filter.equals("limit")) {
                    l = PerlaController.getAttitudeValues(s.getSensoriPK().getIdNodo(), s.getSensoriPK().getIdSensore(), Integer.parseInt(request.getParameter("max")));
                } else if (filter.equals("date")) {
                    l = PerlaController.getAttitudeValuesByDate(s.getSensoriPK().getIdNodo(), s.getSensoriPK().getIdSensore(), Long.parseLong(request.getParameter("from")), Long.parseLong(request.getParameter("to")));
                }
                for (Attitude a : l) {
                    i += "<value>"
                            + "<timestamp>" + a.getAttitudePK().getTimestamp() + "</timestamp>"
                            + "<attitudeX>" + a.getAttitudeX() + "</attitudeX>"
                            + "<attitudeY>" + a.getAttitudeY() + "</attitudeY>"
                            + "<attitudeZ>" + a.getAttitudeZ() + "</attitudeZ>"
                            + "</value>";
                }
            } else if (s.getTiposensore().getNome().equals("temperature")) {
                List<Temperature> l = null;
                if (filter.equals("limit")) {
                    l = PerlaController.getTemperatureValues(s.getSensoriPK().getIdNodo(), s.getSensoriPK().getIdSensore(), Integer.parseInt(request.getParameter("max")));
                } else if (filter.equals("date")) {
                    l = PerlaController.getTemperatureValuesByDate(s.getSensoriPK().getIdNodo(), s.getSensoriPK().getIdSensore(), Long.parseLong(request.getParameter("from")), Long.parseLong(request.getParameter("to")));
                }
                for (Temperature t : l) {
                    i += "<value>"
                            + "<timestamp>" + t.getTemperaturePK().getTimestamp() + "</timestamp>"
                            + "<valore>" + t.getValue() + "</valore>"
                            + "</value>";
                }
            } else if (s.getTiposensore().getNome().equals("geophone")) {
                List<Bibi> l = null;
                if (filter.equals("limit")) {
                    l = PerlaController.getBibiValues(s.getSensoriPK().getIdNodo(), s.getSensoriPK().getIdSensore(), Integer.parseInt(request.getParameter("max")));
                } else if (filter.equals("date")) {
                    l = PerlaController.getBibiValuesByDate(s.getSensoriPK().getIdNodo(), s.getSensoriPK().getIdSensore(), Long.parseLong(request.getParameter("from")), Long.parseLong(request.getParameter("to")));
                }
                for (Bibi b : l) {
                    i += "<value>"
                            + "<data>" + b.getData() + "</data>"
                            + "<timestamp>" + b.getBibiPK().getTimestamp() + "</timestamp>"
                            + "<flags>" + b.getFlags() + "</flags>"
                            + "<samples>" + b.getSamples() + "</samples>"
                            + "<magnitudeX>" + b.getMagnitudex() + "</magnitudeX>"
                            + "<magnitudeY>" + b.getMagnitudey() + "</magnitudeY>"
                            + "<magnitudeZ>" + b.getMagnitudez() + "</magnitudeZ>"
                            + "<peakX>" + b.getPeakx() + "</peakX>"
                            + "<peakY>" + b.getPeaky() + "</peakY>"
                            + "<peakZ>" + b.getPeakz() + "</peakZ>"
                            + "<noiseX>" + b.getNoisex() + "</noiseX>"
                            + "<noiseY>" + b.getNoisey() + "</noiseY>"
                            + "<noiseZ>" + b.getNoisez() + "</noiseZ>"
                            + "<samplingTimeStamp>" + b.getSamplingTimestamp() + "</samplingTimeStamp>"
                            + "</value>";
                }
            } else if (s.getTiposensore().getNome().equals("crackmeter")) {
                List<Crackmeter> l = null;
                if (filter.equals("limit")) {
                    l = PerlaController.getCrackmeterValues(s.getSensoriPK().getIdNodo(), s.getSensoriPK().getIdSensore(), Integer.parseInt(request.getParameter("max")));
                } else if (filter.equals("date")) {
                    l = PerlaController.getCrackmeterValuesByDate(s.getSensoriPK().getIdNodo(), s.getSensoriPK().getIdSensore(), Long.parseLong(request.getParameter("from")), Long.parseLong(request.getParameter("to")));
                }
                for (Crackmeter c : l) {
                    i += "<value>"
                            + "<timestamp>" + c.getCrackmeterPK().getTimestamp() + "</timestamp>"
                            + "<valore>" + c.getCrackMeter() + "</valore>"
                            + "</value>";
                }
            }
        } catch (NoSuchSensorException_Exception ex) {
            Logger.getLogger(ValueServlet.class.getName()).log(Level.SEVERE, null, ex);
            i = "<error><message>No sensor found</message></error>";
        } catch (WrongSensorTypeException_Exception ex) {
            Logger.getLogger(ValueServlet.class.getName()).log(Level.SEVERE, null, ex);
            i = "<error><message>Wrong sensor type</message></error>";
        } catch (NullAttributeException ex) {
            i = "<error><message>Empty attribute value</message></error>";
        } finally {
            out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>" + i + "</root>");
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
